<template>
  <div
    v-if="displayText"
    :class="[
      'countdown',
      {
        'not-started': !hasStarted && !hasEnded,
        ended: hasEnded
      }
    ]"
    :style="styleObject"
  >
   距结束：{{ displayText }}
  </div>
</template>

<script lang="ts" setup>
  import { ref, computed, onMounted, onBeforeUnmount } from 'vue'

  interface Props {
    startTime: string | number | Date
    endTime: string | number | Date
    color?: string
  }

  const props = defineProps<Props>()

  const now = ref(Date.now())

  const startTimestamp = computed(() => new Date(props.startTime).getTime())
  const endTimestamp = computed(() => new Date(props.endTime).getTime())

  const hasStarted = computed(() => now.value >= startTimestamp.value)
  const hasEnded = computed(() => now.value >= endTimestamp.value)

  const displayText = ref('')
  let timer: any

  const formatTime = (ms: number) => {
    const totalSeconds = Math.floor(ms / 1000)
    const days = Math.floor(totalSeconds / 86400)
    const hours = Math.floor((totalSeconds % 86400) / 3600)
    const minutes = Math.floor((totalSeconds % 3600) / 60)
    const seconds = totalSeconds % 60
    return `${days}天${pad(hours)}:${pad(minutes)}:${pad(seconds)}`
  }

  const pad = (n: number) => (n < 10 ? '0' + n : '' + n)

  const update = () => {
    now.value = Date.now()

    if (!hasStarted.value) {
      const diff = startTimestamp.value - now.value
      displayText.value = `距开始${formatTime(diff)}`
    } else if (!hasEnded.value) {
      const diff = endTimestamp.value - now.value
      displayText.value = formatTime(diff)
    } else {
      displayText.value = '已结束'
      clearInterval(timer)
    }
  }

  onMounted(() => {
    update()
    timer = setInterval(update, 1000)
  })

  onBeforeUnmount(() => {
    clearInterval(timer)
  })

  // ============ 动态颜色样式 ============
  const mainColor = computed(() => props.color || '#FF0000')
  const rgb = computed(() => hexToRgb(mainColor.value))
  const lightBg = computed(() => `rgba(${rgb.value}, 0.1)`)

  const styleObject = computed(() => {
    return {
      color: mainColor.value,
      // backgroundColor: !hasStarted.value && !hasEnded.value ? lightBg.value : 'transparent'
      // backgroundColor: lightBg.value
    }
  })

  // HEX 转 RGB 辅助函数
  function hexToRgb(hex: string): string {
    const sanitized = hex.replace('#', '')
    const bigint = parseInt(sanitized, 16)
    const r = (bigint >> 16) & 255
    const g = (bigint >> 8) & 255
    const b = bigint & 255
    return `${r}, ${g}, ${b}`
  }
</script>

<style scoped>
  .countdown {
    padding: 2px 6px;
    font-size: 14px;
    display: inline-block;
    width: fit-content;
    border-radius: 10px;
  }
</style>
